class Solution(object):
    def lowestCommonAncestor(self, root, nodes):
        d = {}
        nodes = set(nodes)

        def dfs(node):
            l_c = 0
            r_c = 0
            if node.left:
                l_c = dfs(node.left)
            if node.right:
                r_c = dfs(node.right)
            if node in nodes:
                base = 1
            else:
                base = 0
            d[node] = base + l_c + r_c
            return d[node]

        def dfs2(node):
            if node.left and d[node.left] == len(nodes):
                return dfs2(node.left)
            if node.right and d[node.right] == len(nodes):
                return dfs2(node.right)
            return node

        dfs(root)
        return dfs2(root)
